'use client';

import React, { useState, useEffect } from 'react';
import {
  Container,
  Box,
  Typography,
  Paper,
  CircularProgress,
  Alert,
  Button,
  Tabs,
  Tab,
  Avatar,
  Badge,
  Chip,
  useTheme,
  alpha,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  DialogContentText,
  IconButton,
  useMediaQuery,
  Fade,
} from '@mui/material';
import {
  Person as PersonIcon,
  Work as WorkIcon,
  School as SchoolIcon,
  EmojiEvents as AwardIcon,
  Business as BusinessIcon,
  Inbox as InboxIcon,
  CameraAlt as CameraAltIcon,
  WorkOutline as WorkOutlineIcon,
  Email as EmailIcon,
  Phone as PhoneIcon,
  LocationOn as LocationOnIcon,
} from '@mui/icons-material';
import { useRouter } from 'next/navigation';
import Navbar from '@/components/Navbar';
import ProfileInfo from '@/components/profile/ProfileInfo';
import WorkExperience from '@/components/profile/WorkExperience';
import Education from '@/components/profile/Education';
import Skills from '@/components/profile/Skills';
import Internships from '@/components/profile/Internships';
import Awards from '@/components/profile/Awards';
import Resume from '@/components/profile/Resume';
import Inbox from '@/components/profile/Inbox';

export default function ProfilePage() {
  const router = useRouter();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));
  const [user, setUser] = useState<any>(null);
  const [workExperiences, setWorkExperiences] = useState<any[]>([]);
  const [educations, setEducations] = useState<any[]>([]);
  const [skills, setSkills] = useState<any[]>([]);
  const [internships, setInternships] = useState<any[]>([]);
  const [awards, setAwards] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [fadeIn, setFadeIn] = useState(false);
  const [tabValue, setTabValue] = useState(0);

  // 收件箱相关状态
  const [inboxItems, setInboxItems] = useState<any[]>([]);
  const [inboxLoading, setInboxLoading] = useState(false);
  const [inboxError, setInboxError] = useState('');
  const [unreadCount, setUnreadCount] = useState(0);

  // 企业模式相关状态
  const [isCompanyAdmin, setIsCompanyAdmin] = useState(false);
  const [companyRole, setCompanyRole] = useState('');
  const [companyVerified, setCompanyVerified] = useState(false);
  const [showCompanyDialog, setShowCompanyDialog] = useState(false);
  const [companyFormData, setCompanyFormData] = useState({
    companyName: '',
    companyRole: '',
    password: '',
  });
  const [companyDialogLoading, setCompanyDialogLoading] = useState(false);
  const [companyDialogError, setCompanyDialogError] = useState('');

  // 头像上传相关状态
  const [avatarDialogOpen, setAvatarDialogOpen] = useState(false);
  const [avatarFile, setAvatarFile] = useState<File | null>(null);
  const [avatarPreview, setAvatarPreview] = useState<string>('');

  // 头像上传处理
  const handleAvatarClick = () => {
    setAvatarDialogOpen(true);
    setAvatarPreview(user?.avatar || '');
  };

  const handleAvatarFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      setAvatarFile(file);
      const reader = new FileReader();
      reader.onload = (e) => {
        setAvatarPreview(e.target?.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleAvatarUpload = async () => {
    if (!avatarFile) return;

    try {
      const formData = new FormData();
      formData.append('avatar', avatarFile);

      const token = localStorage.getItem('token');
      const response = await fetch('/api/profile/avatar', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`
        },
        body: formData
      });

      if (response.ok) {
        const result = await response.json();
        setUser((prev: any) => ({ ...prev, avatar: result.avatarUrl }));
        setAvatarDialogOpen(false);
        setAvatarFile(null);
        setAvatarPreview('');
        alert('头像上传成功！');
      } else {
        throw new Error('头像上传失败');
      }
    } catch (error) {
      console.error('头像上传失败:', error);
      alert('头像上传失败，请重试');
    }
  };

  const fetchUserData = async () => {
    setLoading(true);
    setError('');

    try {
      // 检查用户是否登录
      const token = localStorage.getItem('token');
      if (!token) {
        console.log('用户未登录，跳转到登录页面');
        router.push('/login');
        return;
      }

      // 构建请求头
      const headers = {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      };

      // 使用新的API路径获取用户资料
      const userProfileResponse = await fetch('/api/profile', { headers });

      // 处理401未授权的情况
      if (userProfileResponse.status === 401) {
        // 清除无效的token和用户数据，然后跳转到登录页
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        localStorage.removeItem('userData');
        console.error('获取用户资料失败: 未授权');
        router.push('/login');
        return;
      }

      // 检查请求是否成功
      if (!userProfileResponse.ok) {
        throw new Error('获取用户资料失败');
      }

      // 解析用户数据
      const profileData = await userProfileResponse.json();

      // 更新用户基本信息
      setUser(profileData.user || profileData);

      // 设置企业模式相关状态
      const userData = profileData.user || profileData;
      setIsCompanyAdmin(userData.is_company_admin || false);
      setCompanyRole(userData.company_role || '');
      setCompanyVerified(userData.company_verified || false);

      // 单独获取其他数据，使用Promise.all并行请求提高加载速度
      try {
        const [workResponse, educationResponse, skillsResponse, internshipsResponse, awardsResponse, inboxResponse] = await Promise.all([
          fetch('/api/user/work-experiences', { headers }),
          fetch('/api/user/education-experiences', { headers }),
          fetch('/api/user/skills', { headers }),
          fetch('/api/profile/internships', { headers }),
          fetch('/api/profile/awards', { headers }),
          fetch('/api/inbox/message', { headers })
        ]);

        setWorkExperiences(workResponse.ok ? await workResponse.json() : []);
        setEducations(educationResponse.ok ? await educationResponse.json() : []);
        setSkills(skillsResponse.ok ? await skillsResponse.json() : []);
        setInternships(internshipsResponse.ok ? await internshipsResponse.json() : []);
        setAwards(awardsResponse.ok ? await awardsResponse.json() : []);
        setInboxItems(inboxResponse.ok ? await inboxResponse.json() : []);
      } catch (err) {
        console.error('获取用户相关数据失败:', err);
        // 设置默认值，避免界面崩溃
        setWorkExperiences([]);
        setEducations([]);
        setSkills([]);
        setInternships([]);
        setAwards([]);
        setInboxItems([]);
      }

      // 本地存储用户数据，方便下次使用
      if (profileData.user) {
        localStorage.setItem('userData', JSON.stringify(profileData.user));
      } else {
        localStorage.setItem('userData', JSON.stringify(profileData));
      }

      // 动画效果
      setFadeIn(true);
    } catch (error) {
      console.error('获取用户数据失败:', error);
      if ((error as Error).message.includes('未登录')) {
        // 如果是未登录错误，直接跳转到登录页
        router.push('/login');
        return;
      }
      setError((error as Error).message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    // 立即检查登录状态
    const token = localStorage.getItem('token');
    if (!token) {
      console.log('用户未登录，跳转到登录页面');
      router.push('/login');
      return;
    }

    // 首先尝试从localStorage获取用户信息，避免页面闪烁
    const storedUserData = localStorage.getItem('userData');
    if (storedUserData) {
      try {
        const parsedData = JSON.parse(storedUserData);
        setUser(parsedData);
      } catch (e) {
        console.error('解析本地存储的用户数据失败:', e);
      }
    }

    // 获取最新数据
    fetchUserData();
  }, [router]);

  // 计算未读消息数量
  useEffect(() => {
    const unread = inboxItems.filter(item => 
      item.type === 'received' && !item.is_read
    ).length;
    setUnreadCount(unread);
  }, [inboxItems]);

  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setTabValue(newValue);
  };

  // 处理企业模式对话框打开
  function handleOpenCompanyDialog() {
    // 企业模式一旦开启不可取消
    if (isCompanyAdmin) {
      alert('企业模式已开启，无法取消');
      return;
    }
    
    setCompanyFormData({
      companyName: user?.company || '',
      companyRole: '',
      password: '',
    });
    setCompanyDialogError('');
    setShowCompanyDialog(true);
  }

  // 处理企业模式对话框关闭
  function handleCloseCompanyDialog() {
    setShowCompanyDialog(false);
    setCompanyDialogError('');
  }

  // 处理表单输入变化
  function handleCompanyFormChange(field: string, value: string) {
    setCompanyFormData(prev => ({
      ...prev,
      [field]: value
    }));
  }

  // 处理企业模式切换
  async function handleToggleCompanyMode() {
    setCompanyDialogLoading(true);
    setCompanyDialogError('');

    try {
      if (!companyFormData.companyName.trim() || !companyFormData.companyRole.trim() || !companyFormData.password.trim()) {
        throw new Error('请填写完整的公司信息和密码');
      }

      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('用户未登录');
      }

      const headers = {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      };

      // 发送请求切换企业模式（只能开启，不能关闭）
      console.log('发送切换企业模式请求:', {
        is_company_admin: true,
        company_role: companyFormData.companyRole,
        company: companyFormData.companyName,
        password: companyFormData.password
      });

      const response = await fetch('/api/profile/toggle-company-mode', {
        method: 'POST',
        headers,
        body: JSON.stringify({
          is_company_admin: true,
          company_role: companyFormData.companyRole,
          company: companyFormData.companyName,
          password: companyFormData.password
        })
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || '操作失败');
      }

      // 更新状态
      setIsCompanyAdmin(true);
      setCompanyRole(companyFormData.companyRole);

      // 显示成功消息
      alert('已切换为企业模式，您现在可以发布招聘公告');

      // 关闭对话框
      setShowCompanyDialog(false);

      // 刷新用户数据
      fetchUserData();
    } catch (error) {
      console.error('切换企业模式失败:', error);
      setCompanyDialogError((error as Error).message);
    } finally {
      setCompanyDialogLoading(false);
    }
  }

  if (loading) {
    return (
      <Container maxWidth="lg" sx={{ py: 4 }}>
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
          <CircularProgress />
        </Box>
      </Container>
    );
  }

  if (error) {
    return (
      <Container maxWidth="lg" sx={{ py: 4 }}>
        <Alert severity="error" sx={{ mt: 4 }}>
          {error}
          <Button 
            onClick={() => window.location.reload()} 
            sx={{ ml: 2 }} 
            size="small"
          >
            重新加载
          </Button>
        </Alert>
      </Container>
    );
  }

  return (
    <Box sx={{ minHeight: '100vh', bgcolor: 'background.default' }}>
      <Container maxWidth="lg" sx={{ py: 4 }}>
        <Fade in={fadeIn} timeout={500}>
          <Box>
            {/* 用户基本信息卡片 */}
            <Paper
              elevation={0}
              sx={{
                p: 4,
                mb: 4,
                borderRadius: 3,
                background: `linear-gradient(135deg, ${alpha(theme.palette.primary.main, 0.05)} 0%, ${alpha(theme.palette.secondary.main, 0.05)} 100%)`,
                border: `1px solid ${alpha(theme.palette.divider, 0.1)}`,
              }}
            >
              <Box sx={{ mb: 3, display: 'flex', alignItems: 'center', gap: 2 }}>
                <Box sx={{ position: 'relative' }}>
                  <Avatar
                    src={user?.avatar || ''}
                    sx={{
                      width: 100,
                      height: 100,
                      fontSize: '2.5rem',
                      bgcolor: theme.palette.primary.main,
                      border: `3px solid ${theme.palette.background.paper}`,
                      boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
                      cursor: 'pointer',
                      '&:hover': {
                        boxShadow: '0 6px 16px rgba(0,0,0,0.2)',
                      }
                    }}
                    onClick={handleAvatarClick}
                  >
                    {user?.username?.charAt(0)?.toUpperCase() || 'U'}
                  </Avatar>
                  <IconButton
                    sx={{
                      position: 'absolute',
                      bottom: -5,
                      right: -5,
                      bgcolor: theme.palette.primary.main,
                      color: 'white',
                      width: 30,
                      height: 30,
                      '&:hover': {
                        bgcolor: theme.palette.primary.dark,
                      }
                    }}
                    onClick={handleAvatarClick}
                  >
                    <CameraAltIcon fontSize="small" />
                  </IconButton>
                </Box>
                <Box>
                  <Typography variant="h4" sx={{ fontWeight: 600 }}>
                    {user?.username || '未设置用户名'}
                  </Typography>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mt: 1 }}>
                    <Button
                      size="small"
                      startIcon={<BusinessIcon fontSize="small" />}
                      variant={isCompanyAdmin ? 'contained' : 'outlined'}
                      color="primary"
                      onClick={handleOpenCompanyDialog}
                      sx={{
                        borderRadius: 2,
                        textTransform: 'none',
                        bgcolor: isCompanyAdmin ? alpha(theme.palette.primary.main, 0.1) : 'transparent',
                      }}
                      disabled={isCompanyAdmin}
                    >
                      {isCompanyAdmin ? '企业模式已开启' : '我是企业负责人'}
                    </Button>
                    {isCompanyAdmin && (
                      <Button
                        size="small"
                        startIcon={<WorkOutlineIcon fontSize="small" />}
                        variant="contained"
                        color="primary"
                        onClick={() => router.push('/profile/job-posts')}
                      >
                        我的招聘公告
                      </Button>
                    )}
                  </Box>
                  {user?.location && (
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, mt: 1 }}>
                      <LocationOnIcon fontSize="small" color="action" />
                      <Typography variant="body2" color="text.secondary">
                        {user.location}
                      </Typography>
                    </Box>
                  )}
                </Box>
              </Box>
            </Paper>

            {/* 标签页导航 */}
            <Paper
              elevation={0}
              sx={{
                borderRadius: 2,
                overflow: 'hidden',
                border: `1px solid ${alpha(theme.palette.divider, 0.1)}`
              }}
            >
              <Tabs 
                value={tabValue} 
                onChange={handleTabChange}
                variant="scrollable"
                scrollButtons="auto"
                sx={{
                  borderBottom: `1px solid ${alpha(theme.palette.divider, 0.1)}`,
                  '& .MuiTab-root': {
                    minHeight: 60,
                    textTransform: 'none',
                    fontSize: '1rem',
                    fontWeight: 500,
                  }
                }}
              >
                <Tab 
                  icon={<PersonIcon />} 
                  label="个人综述" 
                  iconPosition="start"
                />
                <Tab 
                  icon={
                    <Badge badgeContent={unreadCount > 0 ? unreadCount : null} color="error">
                      <InboxIcon />
                    </Badge>
                  } 
                  label={
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      我的消息
                      {unreadCount > 0 && (
                        <Typography 
                          variant="caption" 
                          sx={{ 
                            color: theme.palette.error.main,
                            fontWeight: 600,
                            animation: 'pulse 1.5s ease-in-out infinite'
                          }}
                        >
                          新消息
                        </Typography>
                      )}
                    </Box>
                  }
                  iconPosition="start"
                />
                <Tab 
                  icon={<WorkIcon />} 
                  label="工作经历" 
                  iconPosition="start"
                />
                <Tab 
                  icon={<SchoolIcon />} 
                  label="教育背景" 
                  iconPosition="start"
                />
                <Tab 
                  icon={<AwardIcon />} 
                  label="技能与成就" 
                  iconPosition="start"
                />
              </Tabs>

              {/* 标签页内容 */}
              <Box sx={{ p: 3 }}>
                {tabValue === 0 && (
                  <Box>
                    <ProfileInfo user={user} onUpdate={fetchUserData} />
                    <Resume user={user} onUpdate={fetchUserData} />
                  </Box>
                )}
                {tabValue === 1 && (
                  <Inbox 
                    inboxItems={inboxItems}
                    isLoading={inboxLoading}
                    error={inboxError}
                    isCompanyAdmin={isCompanyAdmin}
                    onUpdate={fetchUserData}
                  />
                )}
                {tabValue === 2 && (
                  <WorkExperience 
                    workExperiences={workExperiences}
                    onUpdate={fetchUserData}
                  />
                )}
                {tabValue === 3 && (
                  <Box>
                    <Education 
                      educations={educations}
                      onUpdate={fetchUserData}
                    />
                    <Box sx={{ mt: 4 }}>
                      <Internships 
                        internships={internships}
                        onUpdate={fetchUserData}
                      />
                    </Box>
                  </Box>
                )}
                {tabValue === 4 && (
                  <Box>
                    <Skills 
                      skills={skills}
                      onUpdate={fetchUserData}
                    />
                    <Box sx={{ mt: 4 }}>
                      <Awards 
                        awards={awards}
                        onUpdate={fetchUserData}
                      />
                    </Box>
                  </Box>
                )}
              </Box>
            </Paper>
          </Box>
        </Fade>
      </Container>

      {/* 头像上传对话框 */}
      <Dialog open={avatarDialogOpen} onClose={() => setAvatarDialogOpen(false)} maxWidth="sm" fullWidth>
        <DialogTitle>更换头像</DialogTitle>
        <DialogContent>
          <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, py: 2 }}>
            <Avatar
              src={avatarPreview || user?.avatar}
              sx={{
                width: 120,
                height: 120,
                fontSize: '3rem',
                bgcolor: theme.palette.primary.main
              }}
            >
              {user?.username?.charAt(0)?.toUpperCase() || 'U'}
            </Avatar>
            
            <input
              accept="image/*"
              style={{ display: 'none' }}
              id="avatar-upload"
              type="file"
              onChange={handleAvatarFileChange}
            />
            <label htmlFor="avatar-upload">
              <Button variant="outlined" component="span" startIcon={<CameraAltIcon />}>
                选择图片
              </Button>
            </label>
            
            {avatarFile && (
              <Typography variant="body2" color="text.secondary">
                已选择: {avatarFile.name}
              </Typography>
            )}
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setAvatarDialogOpen(false)}>取消</Button>
          <Button onClick={handleAvatarUpload} variant="contained" disabled={!avatarFile}>
            上传
          </Button>
        </DialogActions>
      </Dialog>

      {/* 企业模式切换对话框 */}
      <Dialog open={showCompanyDialog} onClose={handleCloseCompanyDialog}>
        <DialogTitle>
          切换为企业模式
        </DialogTitle>
        <DialogContent>
          {companyDialogError && (
            <Alert severity="error" sx={{ mb: 2 }}>
              {companyDialogError}
            </Alert>
          )}
          <DialogContentText>
            切换为企业模式后，您可以发布招聘公告。注意：企业模式一旦开启将无法取消。请填写以下信息：
          </DialogContentText>

          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, mt: 2 }}>
            <TextField
              margin="dense"
              label="公司名称"
              type="text"
              fullWidth
              variant="outlined"
              value={companyFormData.companyName}
              onChange={(e) => handleCompanyFormChange('companyName', e.target.value)}
              placeholder="请输入您所在的公司名称"
            />

            <TextField
              margin="dense"
              label="您在公司的职位"
              type="text"
              fullWidth
              variant="outlined"
              value={companyFormData.companyRole}
              onChange={(e) => handleCompanyFormChange('companyRole', e.target.value)}
              placeholder="例如：人力资源经理、技术总监等"
            />

            <TextField
              margin="dense"
              label="确认密码"
              type="password"
              fullWidth
              variant="outlined"
              value={companyFormData.password}
              onChange={(e) => handleCompanyFormChange('password', e.target.value)}
              placeholder="请输入您的账户密码以确认身份"
            />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseCompanyDialog}>取消</Button>
          <Button
            onClick={handleToggleCompanyMode}
            variant="contained"
            color="primary"
            disabled={companyDialogLoading}
            startIcon={companyDialogLoading && <CircularProgress size={20} />}
          >
            {companyDialogLoading ? '处理中...' : '切换为企业模式'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}